import 'package:cunyutech_flutter_ui/cunyutech_flutter_ui.dart';
import 'package:flutter/widgets.dart';

typedef Widget OverlayWidgetBuilder(BuildContext context, OverlaySupportState state);

OverlayEntry showOverlay({
  OverlayWidgetBuilder builder,
}) {
  OverlaySupportState supportState = OverlaySupport.of(_keyFinder.currentContext);
  OverlayEntry entry = OverlayEntry(builder: (_)=> builder(_, supportState));
  supportState.overlay.insert(entry);
  return entry;
}

class OverlaySupport extends StatefulWidget {
  OverlaySupport({Key key, this.child, this.colorSystem }) : super(key: key);

  final Widget child;
  final ColorSystem colorSystem;

  static OverlaySupportState of(BuildContext context) {
    return context.findRootAncestorStateOfType<OverlaySupportState>();
  }

  @override
  OverlaySupportState createState() => OverlaySupportState();
}

class OverlaySupportState extends State<OverlaySupport> {

  List<OverlayEntry> entrys = [];

  OverlayState get overlay {
    NavigatorState navigator;
    void visitor(Element element) {
      if (navigator != null) return;
      if (element.widget is Navigator) {
        navigator = (element as StatefulElement).state;
      } else {
        element.visitChildElements(visitor);
      }
    }
    context.visitChildElements(visitor);
    return navigator.overlay;
  }

  ColorSystem get colorSystem {
    return widget.colorSystem;
  }

  @override
  Widget build(BuildContext context) {
    return CYThemeData(
      colorSystem: widget.colorSystem,
      child: _OverlayFinder(
        key: _keyFinder,
        child: widget.child
      )
    );
  }
}

final GlobalKey<_OverlayFinderState> _keyFinder = GlobalKey(debugLabel: 'overlay_support');
/// Used to find the [Overlay] in decedents tree.
class _OverlayFinder extends StatefulWidget {
  final Widget child;

  const _OverlayFinder({Key key, this.child}) : super(key: key);

  @override
  _OverlayFinderState createState() => _OverlayFinderState();
}

class _OverlayFinderState extends State<_OverlayFinder> {
  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
